package cn.stylefeng.guns.modular.gridsystem.timer;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.stylefeng.guns.core.timer.TimerTaskRunner;
import cn.stylefeng.guns.modular.gridsystem.entity.BizGatewayChannel;
import cn.stylefeng.guns.modular.gridsystem.entity.BizUploadScore;
import cn.stylefeng.guns.modular.gridsystem.service.BizGatewayChannelService;
import cn.stylefeng.guns.modular.gridsystem.service.BizUploadScoreService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 定时更新通道为离线状态
 * @author ssy
 * @date 2022/6/20 17:33
 */
@Component
@Slf4j
public class ChannelStatueTaskRunner implements TimerTaskRunner {

    @Resource
    private BizGatewayChannelService bizGatewayChannelService;

    @Resource
    private BizUploadScoreService bizUploadScoreService;

    @Override
    public void action() {
        List<BizGatewayChannel> list = bizGatewayChannelService.list();
        DateTime dateTime = DateUtil.offsetMinute(new Date(), -3);
        LambdaQueryWrapper<BizUploadScore> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(BizUploadScore::getId,BizUploadScore::getDeviceId,BizUploadScore::getGatewayChannel,BizUploadScore::getGatewayId)
            .ge(BizUploadScore::getCreatedAt,dateTime)
            .groupBy(BizUploadScore::getId,BizUploadScore::getDeviceId,BizUploadScore::getGatewayChannel,BizUploadScore::getGatewayId);
        List<BizUploadScore> uploadScoreList = bizUploadScoreService.list(queryWrapper);
        A:for (BizGatewayChannel bizGatewayChannel:list){
            for (BizUploadScore bizUploadScore:uploadScoreList) {
                if(Objects.equals(bizUploadScore.getDeviceId(), bizGatewayChannel.getDeviceId())&&Objects.equals(bizUploadScore.getGatewayId(),bizGatewayChannel.getGatewayId())&&Objects.equals(bizUploadScore.getGatewayChannel(),bizGatewayChannel.getChannel())){
                    continue A;
                }
            }
            LambdaUpdateWrapper<BizGatewayChannel> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(BizGatewayChannel::getId,bizGatewayChannel.getId());
            wrapper.set(BizGatewayChannel::getStatus,0);
            bizGatewayChannelService.update(wrapper);
        }
    }

}
